package com.lanchewuyou.user.driver.lipeiui;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.lanchewuyou.user.driver.R;
import com.lanchewuyou.user.driver.adapter.FoursAdapter;
import com.lanchewuyou.user.driver.bean.FourS;
import com.lanchewuyou.user.driver.bean.FoursDB;
import com.lanchewuyou.user.driver.ui.StartDaohangActivity;
import com.lanchewuyou.user.driver.modul.Config;
import com.lanchewuyou.user.driver.modul.OkHttpClientManager;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.squareup.okhttp.Request;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 输入4S店,修理厂页面
 */
public class CompanyActivity extends AppCompatActivity {
    private Toolbar mToolbar;
    private MaterialEditText foursName;
    private ListView foursListview;
    private TextView foursAdd;
    List<FourS> mData = new ArrayList<>();//动态数据
    List<FourS> staticData = new ArrayList<>();//静态数据
    private String foursId = "0";
    private FoursDB foursDB;
    private FoursAdapter foursAdapter;
    Handler myhandler = new Handler();
    private Spinner companySpinner;
    private List<String> citylists;
    private ArrayAdapter<String> spinneradapter;
    private CheckBox isFix, isReturnCar;
    private MaterialEditText xiulichang, returnCarAdd;
    private Button companyNextBtn;
    private int isHuanche = 0;
    private ProgressDialog progressDialog;
    private ProgressDialog progressUploadDialog;
    private static String DRIVERID;

    public static CompanyActivity instance;
    private Toast toast1 = null;

    private void showTextToast(String msg) {
        if (toast1 == null) {
            toast1 = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
        } else {
            toast1.setText(msg);
        }
        toast1.show();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_company);
        initViews();
        progressDialog.show();
        instance = this;
        SharedPreferences sharedPreferences = getSharedPreferences(Config.PASSWORD_PATH, Activity.MODE_PRIVATE);
        DRIVERID = sharedPreferences.getString("driverid", "");
        set_mListView_adapter();//给listview控件添加一个adapter
        set_eSearch_TextChanged();//设置eSearch搜索框的文本改变时监听器
        OkHttpClientManager.getAsyn(Config.DRIVERORDERDETAIL + "&driverid=" + DRIVERID + "&orderid=" + PickCarActivity.orderId, new OkHttpClientManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                showTextToast("没有获取到详情");
                progressDialog.dismiss();
            }

            @Override
            public void onResponse(String response) {
                Log.d("Pickcar", response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString("status");
                    if (status.equals("1")) {
                        JSONObject info = jsonObject.getJSONObject("info");
                        foursName.setText(info.getJSONObject("shopinfo").getString("name") + " ");
                        foursAdd.setText(info.getJSONObject("shopinfo").getString("address"));
                        String fourid = info.getJSONObject("shopinfo").getString("id");
                        if (fourid.equals("0") || fourid.equals("")) {
                            foursId = "0";
                        } else {
                            foursId = fourid;
                        }
                        String xiu = info.getString("shopname");
                        String caradd = info.getString("address");
                        if (xiu.length() == 0) {
                            isFix.setChecked(false);
                            xiulichang.setEnabled(false);
                        } else {
                            isFix.setChecked(true);
                        }
                        if (caradd.length() == 0) {
                            isHuanche = 0;
                            isReturnCar.setChecked(false);
                            returnCarAdd.setEnabled(false);
                        } else {
                            isHuanche = 1;
                            isReturnCar.setChecked(true);
                        }
                        xiulichang.setText(info.getString("shopname"));
                        returnCarAdd.setText(info.getString("address"));
                        progressDialog.dismiss();
                    } else {
                        showTextToast("没有获取到详情");
                        progressDialog.dismiss();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    progressDialog.dismiss();
                }
            }
        });
    }

    private void initViews() {
        mToolbar = (Toolbar) findViewById(R.id.company_toolbar);
        mToolbar.setTitle("送修信息确认");
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        isFix = (CheckBox) findViewById(R.id.is_fix);
        isFix.setChecked(false);
        isFix.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    foursName.setEnabled(false);
                    xiulichang.setEnabled(true);
                    foursName.setText("");
                    foursAdd.setText("");
                    foursId = "0";
                } else if (!isChecked) {
                    foursName.setEnabled(true);
                    xiulichang.setEnabled(false);
                    xiulichang.setText("");
                }
            }
        });
        isReturnCar = (CheckBox) findViewById(R.id.is_return_car);
        isReturnCar.setChecked(false);
        isReturnCar.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    returnCarAdd.setEnabled(true);
                    isHuanche = 1;
                } else if (!isChecked) {
                    returnCarAdd.setEnabled(false);
                    returnCarAdd.setText("");
                    isHuanche = 0;
                }
            }
        });
        xiulichang = (MaterialEditText) findViewById(R.id.xiulichang_edittext);
        xiulichang.setEnabled(false);
        returnCarAdd = (MaterialEditText) findViewById(R.id.return_car_add);
        returnCarAdd.setEnabled(false);
        foursAdd = (TextView) findViewById(R.id.fours_add);
        companyNextBtn = (Button) findViewById(R.id.company_next_btn);
        companyNextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                progressUploadDialog.show();
                Log.d("company", Config.COMPANYINFO + PickCarActivity.orderId + "&driverid=" + DRIVERID +
                        "&shopid=" + foursId + "&shopname=" + xiulichang.getText().toString() + "&huanche=" + isHuanche +
                        "&address=" + returnCarAdd.getText().toString());
                if (foursId.equals("0") && TextUtils.isEmpty(xiulichang.getText().toString())) {
                    showTextToast("有信息未完善");
                    progressUploadDialog.dismiss();
                } else {
                    OkHttpClientManager.getAsyn(Config.COMPANYINFO + PickCarActivity.orderId + "&driverid=" + DRIVERID +
                            "&shopid=" + foursId + "&shopname=" + xiulichang.getText().toString() + "&huanche=" + isHuanche +
                            "&address=" + returnCarAdd.getText().toString(), new OkHttpClientManager.StringCallback() {
                        @Override
                        public void onFailure(Request request, IOException e) {
                            showTextToast("上传失败");
                            progressUploadDialog.dismiss();
                        }

                        @Override
                        public void onResponse(String response) {
                            Log.d("company", response);
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                String status = jsonObject.getString("status");
                                if (status.equals("1")) {
                                    Intent intent = new Intent(CompanyActivity.this, StartDaohangActivity.class);
                                    intent.putExtra("from", "pickcar");
                                    startActivity(intent);
                                    finish();
                                    progressUploadDialog.dismiss();
                                } else {
                                    progressUploadDialog.dismiss();
                                    showTextToast("请求失败");
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                                progressUploadDialog.dismiss();
                            }
                        }
                    });
                }
            }
        });
        progressDialog = new ProgressDialog(CompanyActivity.this);
        progressDialog.setMessage("请稍等");
        progressDialog.setTitle("加载中");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setCancelable(true);
        progressUploadDialog = new ProgressDialog(CompanyActivity.this);
        progressUploadDialog.setMessage("请稍等");
        progressUploadDialog.setTitle("上传中");
        progressUploadDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressUploadDialog.setCancelable(true);
        companySpinner = (Spinner) findViewById(R.id.company_spinner);
        citylists = new ArrayList<>();
        citylists.add("北京");
        citylists.add("上海");
        citylists.add("杭州");
        citylists.add("深圳");
        spinneradapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, citylists);
        spinneradapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        companySpinner.setAdapter(spinneradapter);
        foursDB = FoursDB.getInstance(this);
        mData = foursDB.findFours();
        staticData = foursDB.findFours();
    }

    /**
     * 设置ListView的Adapter，包含两个元素，4S店名称和地点
     */
    private void set_mListView_adapter() {
        foursListview = (ListView) findViewById(R.id.company_list);
        foursAdapter = new FoursAdapter(mData, CompanyActivity.this);
        foursListview.setAdapter(foursAdapter);
    }

    /**
     * 设置搜索框的文本更改时的监听器
     */
    private void set_eSearch_TextChanged() {
        foursName = (MaterialEditText) findViewById(R.id.fours_name);
        foursName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    foursListview.setVisibility(View.GONE);
                }
            }
        });
        foursName.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                          int arg3) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                /**
                 * 这是文本框改变之后 会执行的动作
                 * 因为我们要做的就是，在文本框改变的同时，我们的listview的数据也进行相应的变动，并且如一的显示在界面上。
                 * 所以这里我们就需要加上数据的修改的动作了。
                 */
                myhandler.post(eChanged);
            }
        });
    }

    /**
     * 异步操作listview
     */
    Runnable eChanged = new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            String data = foursName.getText().toString();
            if (foursName.getText().length() != 0) {
                mData.clear();//先要清空，不然会叠加
                getmDataSub(mData, data);//获取更新数据
                foursAdapter.notifyDataSetChanged();//更新
                foursListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        foursName.setText(mData.get(position).getName() + " ");//加一个空格暂时解决点击listview选择item后listview不消失的问题，还要想办法解决
                        foursAdd.setText(mData.get(position).getAddress());
                        foursId = mData.get(position).getId();
                        foursListview.setVisibility(View.GONE);
                        //收起键盘
                        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(foursName.getWindowToken(), 0);
                    }
                });
            } else {
                foursListview.setVisibility(View.GONE);
            }
        }
    };

    /**
     * 获得根据搜索框的数据data来从元数据筛选，筛选出来的数据放入mDataSubs里
     */
    private void getmDataSub(List<FourS> fourSes, String data) {
        int length = staticData.size();
        for (int i = 0; i < length; ++i) {
            if (staticData.get(i).getName().contains(data) || staticData.get(i).getAddress().contains(data)) {
                foursListview.setVisibility(View.VISIBLE);
                fourSes.add(staticData.get(i));
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_company, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            showBackDialog();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        showBackDialog();
    }

    private void showBackDialog() {
        new MaterialDialog.Builder(this)
                .title("退出任务")
                .content("点击确定将退出您正在执行的任务。")
                .positiveText("确定")
                .negativeText("取消")
                .callback(new MaterialDialog.ButtonCallback() {
                    @Override
                    public void onPositive(MaterialDialog dialog) {
                        finish();
                    }

                    @Override
                    public void onNegative(MaterialDialog dialog) {
                        super.onNegative(dialog);
                    }
                })
                .show();
    }

}
